package cn.angis.system.service;

import cn.angis.common.constant.Constant;
import cn.angis.db.service.BaseService;
import cn.angis.system.dto.output.LoginOutput;
import cn.angis.system.model.User;
import cn.angis.system.model.Userpost;
import cn.angis.system.model.Userrole;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import org.noear.solon.annotation.Inject;
import org.noear.solon.annotation.ProxyComponent;
import org.sagacity.sqltoy.model.EntityQuery;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 包名称：cn.angis.system.service
 * 类名称：SysUserService
 * 类描述：系统用户服务
 * 创建人：@author angis.cn
 * 创建日期： 2022/12/30 17:39
 */
@ProxyComponent
public class UserService extends BaseService<User> {

    @Inject
    private UserroleService userroleService;

    @Inject
    private UserpostService userpostService;

    @Inject
    private RoleresService roleresService;

    public User getByUserName(String userName) {
        return dao.loadEntity(User.class, EntityQuery.create().where("del_flag='0' #[and username=:userName]")
                .names("userName").values(userName));
    }

    public void refreshUserByUserId(String userId) {
        SaSession session = StpUtil.getSessionByLoginId(userId, false);
        if (session != null) {
            List<String> roleAndResourceByUserId = roleresService.getRoleAndResourceByUserId(userId);
            LoginOutput loginOutput = session.getModel(Constant.SESSION_USER_KEY, LoginOutput.class);
            loginOutput.setResources(roleAndResourceByUserId);
            session.set(Constant.SESSION_USER_KEY, loginOutput);
        }
    }

    public List<String> getPostListByUserId(String userId) {
        return dao.findEntity(Userpost.class, EntityQuery.create()
                .where("#[userId=:userId]")
                .values(userId)).stream().map(Userpost::getPostId)
                .collect(Collectors.toList());
    }

    public List<String> getRoleListByUserId(String userId) {
        return dao.findEntity(Userrole.class, EntityQuery.create()
                .where("#[userId=:userId]")
                .values(userId)).stream().map(Userrole::getRoleId)
                .collect(Collectors.toList());
    }

}
